package self.hoy.demo.grainmall.cart.interceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import self.hoy.demo.common.constant.AuthServerConstant;
import self.hoy.demo.common.constant.CartConstant;
import self.hoy.demo.common.to.MemberTo;
import self.hoy.demo.grainmall.cart.vo.UserInfoTo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author hyh
 * @date 2020/8/17
 */
public class CartInterceptor implements HandlerInterceptor {

    /**
     * cookie 跨域保存的域名
     */
    private String domain;

    /**
     * 线程内共享
     */
    public static ThreadLocal<UserInfoTo> threadLocal;

    static {
        threadLocal = new ThreadLocal<>();
    }

    public CartInterceptor(String domain) {
        this.domain = domain;
    }

    /**
     * 进入Controller之前判断是否放行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberTo member = (MemberTo) session.getAttribute(AuthServerConstant.USER_SESSION_KEY);
        UserInfoTo user = new UserInfoTo();
        if (member == null) {//TODO 区分购物车商品和session的redis database
            Cookie cookie = get(request.getCookies());
            if (cookie != null) {
                user.setUserKey(cookie.getValue());
                user.setTempUser(true);
            }
        } else {//有登录
            user.setUserId(member.getId());
        }
        if (StringUtils.isEmpty(user.getUserKey())) {
            user.setUserKey(UUID.randomUUID().toString());
        }
        threadLocal.set(user);
        return true;
    }

    private Cookie get(Cookie[] cookies) {
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 业务执行之后，分配临时用户，让浏览器保存
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo user = threadLocal.get();
        if (user.isTempUser()) {
            return;
        }
//        Cookie cookie = get(request.getCookies());
        Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, user.getUserKey());
        cookie.setDomain(domain);
        cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);

        response.addCookie(cookie);
    }
}
